#include "NIBase.h"


NIBase::NIBase():m_Context(0),m_DepthGenerator(0),m_ImageGenerator(0),m_UserGenerator(0)
{
}

NIBase::~NIBase()
{
	m_Context.Release();
	m_DepthGenerator.Release();
	m_ImageGenerator.Release();
	m_UserGenerator.Release();
}

bool NIBase::Initialize( int width,int height,int fps )
{
	XnStatus eResult;
	// Initial context
	eResult = m_Context.Init();
	if( !CheckOpenNIError( eResult, "Initialize context" ) )
	{
		return false;
	}
	// Set map mode
	m_MapMode.nXRes = width;
	m_MapMode.nYRes = height;
	m_MapMode.nFPS = fps;
	// Create image generator
	eResult = m_ImageGenerator.Create( m_Context );
	if( !CheckOpenNIError( eResult, "Create image generator" ) )
	{
		return false;
	}
	eResult = m_ImageGenerator.SetMapOutputMode( m_MapMode );
	if( !CheckOpenNIError( eResult, "m_ImageGenerator SetMapOutputMode" ) )
	{
		return false;
	}
	// Create depth generator
	eResult = m_DepthGenerator.Create( m_Context );
	if( !CheckOpenNIError( eResult, "Create depth generator" ) )
	{
		return false;
	}
	eResult = m_DepthGenerator.SetMapOutputMode( m_MapMode );
	if( !CheckOpenNIError( eResult, "m_DepthGenerator SetMapOutputMode" ) )
	{
		return false;
	}
	eResult = m_DepthGenerator.GetAlternativeViewPointCap().SetViewPoint( m_ImageGenerator );
	if( !CheckOpenNIError( eResult, "m_DepthGenerator SetViewPoint" ) )
	{
		return false;
	}
	// Create user generator
	eResult = m_UserGenerator.Create( m_Context );
	if( !CheckOpenNIError( eResult, "Create user generator" ) )
	{
		return false;
	}

	eResult = m_UserGenerator.GetSkeletonCap().SetSmoothing(0.8);//Set smoothing
	if( !CheckOpenNIError( eResult, "Set user generator smoothing" ) )
	{
		return false;
	}
	return InitContent();
}

bool NIBase::CheckOpenNIError( XnStatus eResult, std::string sStatus /*= "no message" */ )
{
	if( eResult != XN_STATUS_OK ){
		//cerr << sStatus << " Error: " << xnGetStatusString( eResult ) << endl;
		printf("OpenNI----Error: %s----\n",sStatus.c_str());
		return false;
	}
	return true;
}

void NIBase::Update()
{
	// Update data
	m_Context.WaitAndUpdateAll();
	// Get image data
	m_ImageGenerator.GetMetaData( m_ColorData );
	// Get depth data
	m_DepthGenerator.GetMetaData( m_DepthData );
	// Get number of users
	m_nUsers = m_UserGenerator.GetNumberOfUsers();
	UpdateContent();
}
